package com.tree.treeoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.tree.treeoj.annotation.AuthCheck;
import com.tree.treeoj.common.BaseResponse;
import com.tree.treeoj.common.DeleteRequest;
import com.tree.treeoj.common.ErrorCode;
import com.tree.treeoj.common.ResultUtils;
import com.tree.treeoj.constant.UserConstant;
import com.tree.treeoj.exception.BusinessException;
import com.tree.treeoj.exception.ThrowUtils;
import com.tree.treeoj.model.dto.comment.*;
import com.tree.treeoj.model.dto.post.PostEditRequest;
import com.tree.treeoj.model.dto.post.PostQueryRequest;
import com.tree.treeoj.model.entity.CommentRelation;
import com.tree.treeoj.model.entity.Post;
import com.tree.treeoj.model.entity.PostComment;
import com.tree.treeoj.model.entity.User;
import com.tree.treeoj.model.vo.CommentVO;
import com.tree.treeoj.model.vo.PostCommentVO;
import com.tree.treeoj.model.vo.PostVO;
import com.tree.treeoj.service.CommentRelationService;
import com.tree.treeoj.service.PostCommentService;
import com.tree.treeoj.service.PostService;
import com.tree.treeoj.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * 评论接口
 */
@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Resource
    private PostCommentService postCommentService;

    @Resource
    private CommentRelationService commentRelationService;

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param postCommentAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加帖子评论")
    public BaseResponse<Long> addPostComment(@RequestBody PostCommentAddRequest postCommentAddRequest, HttpServletRequest request) {
        if (postCommentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        postCommentAddRequest.setUserId(loginUser.getId());
        PostComment postComment = new PostComment();
        BeanUtils.copyProperties(postCommentAddRequest, postComment);
        postComment.setFatherId(UUID.randomUUID().toString());
        postCommentService.validPostComment(postComment, true);
        boolean result = postCommentService.save(postComment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long postCommentId = postComment.getId();
        return ResultUtils.success(postCommentId);
    }

    /**
     * 创建
     *
     * @param commentRelationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/addComment")
    @ApiOperation(value = "添加二级评论")
    public BaseResponse<Long> addComment(@RequestBody CommentRelationAddRequest commentRelationAddRequest, HttpServletRequest request) {
        if (commentRelationAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        commentRelationAddRequest.setUserId(loginUser.getId());
        commentRelationAddRequest.setSonId(UUID.randomUUID().toString());
        CommentRelation commentRelation = new CommentRelation();
        BeanUtils.copyProperties(commentRelationAddRequest,commentRelation);
        commentRelationService.validComment(commentRelation,true);
        boolean result = commentRelationService.save(commentRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long commentRelationId = commentRelation.getId();
        return ResultUtils.success(commentRelationId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除评论")
    public BaseResponse<Boolean> deletePostComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        PostComment postComment = postCommentService.getById(id);
        ThrowUtils.throwIf(postComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!postComment.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = postService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param postCommentUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新评论")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePostComment(@RequestBody PostCommentUpdateRequest postCommentUpdateRequest) {
        if (postCommentUpdateRequest == null || postCommentUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = postCommentUpdateRequest.getId();
        // 判断是否存在
        PostComment oldPostComment = postCommentService.getById(id);
        ThrowUtils.throwIf(oldPostComment == null, ErrorCode.NOT_FOUND_ERROR);
        BeanUtils.copyProperties(postCommentUpdateRequest, oldPostComment);
        // 参数校验
        postCommentService.validPostComment(oldPostComment, false);
        boolean result = postCommentService.updateById(oldPostComment);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据 id 获取评论")
    public BaseResponse<PostCommentVO> getPostCommentVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        PostComment postComment = postCommentService.getById(id);
        if (postComment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(postCommentService.getPostCommentVO(postComment, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postCommentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostCommentVO>> listPostCommentVOByPage(@RequestBody PostCommentQueryRequest postCommentQueryRequest,
                                                                     HttpServletRequest request) {
        long current = postCommentQueryRequest.getCurrent();
        long size = postCommentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<PostComment> postCommentPage = postCommentService.page(new Page<>(current, size),
                postCommentService.getQueryWrapper(postCommentQueryRequest));
        return ResultUtils.success(postCommentService.getPostCommentVOPage(postCommentPage, request));
    }
    /**
     * 分页获取二级评论列表（封装类）
     *
     * @param commentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/comment")
    public BaseResponse<Page<CommentVO>> listCommentVOByPage(@RequestBody CommentQueryRequest commentQueryRequest,
                                                                 HttpServletRequest request) {
        long current = commentQueryRequest.getCurrent();
        long size = commentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<CommentRelation> commentPage = commentRelationService.page(new Page<>(current, size),
                commentRelationService.getQueryWrapper(commentQueryRequest));
        return ResultUtils.success(commentRelationService.getCommentVOPage(commentPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostVO>> listMyPostCommentVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                                HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        postQueryRequest.setUserId(loginUser.getId());
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    // endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<PostVO>> searchPostCommentVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                                HttpServletRequest request) {
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.searchFromEs(postQueryRequest);
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param postEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPostComment(@RequestBody PostEditRequest postEditRequest, HttpServletRequest request) {
        if (postEditRequest == null || postEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postEditRequest, post);
        List<String> tags = postEditRequest.getTags();
        if (tags != null) {
            post.setTags(GSON.toJson(tags));
        }
        // 参数校验
        postService.validPost(post, false);
        User loginUser = userService.getLoginUser(request);
        long id = postEditRequest.getId();
        // 判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }

}
